/**
 * Copyright 2014 lerry
 * 
 * All right reserved.
 * 
 * Dec 14, 2014
 */
package com.bac.bacplatform;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.android.volley.Response.Listener;
import com.bac.javabeans.FuellingCard;
import com.bac.javabeans.Page;
import com.bac.javabeans.Principal;
import com.bac.utils.Config;
import com.bac.utils.Util;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * 油卡直充
 * @author lerry
 * 
 */
public class RechargeActivity extends BaseActivity implements OnClickListener{

	// 手动输入开关
	private CheckBox mCheckBoxInput;
	// 是否手动输入
	private boolean mIsManual = false;
	// 手动输入框
	private EditText mEtInpu;

	// 聚优金余额
	private TextView mTvRemaining;

	// 当前选择支付方式，0(未选择)，1(聚优金)，2(银行卡)
	private int mCurrentPay = 0;
	// 选择支付方式的控件
	private CheckBox checkBox1, checkBox2, checkBox3;

	// 选择金额
	private Spinner mChargeSpinner;
	private ArrayAdapter<String> mChareAdapter;
	// 选择的金额
	private String mPayAmount = "";
	
	private ArrayAdapter<String> mAdapter;
	
	
	// 卡号数据
	private ArrayList<String> mCardStrings = new ArrayList<String>();
	private ArrayList<String> mCardNameString = new ArrayList<String>();
	
	private AutoCompleteTextView mAtCard;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.recharge_main);

		// 卡号
		mAtCard = (AutoCompleteTextView) findViewById(R.id.et_card_num);
		// 手动输入金额
		mEtInpu = (EditText) findViewById(R.id.et_charge_manual);

		mTvRemaining = (TextView) findViewById(R.id.tv_remaining);

		mCheckBoxInput = (CheckBox) findViewById(R.id.cb_input_manual);
		mCheckBoxInput
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						mIsManual = isChecked;
						if (mIsManual) {
							findViewById(R.id.rl_charge_manual).setVisibility(
									View.VISIBLE);
							findViewById(R.id.rl_charge_select).setVisibility(
									View.GONE);
						} else {
							findViewById(R.id.rl_charge_manual).setVisibility(
									View.GONE);
							findViewById(R.id.rl_charge_select).setVisibility(
									View.VISIBLE);
						}
					}
				});
		
		mAdapter = new ArrayAdapter<String>(this, R.layout.drop_down_item, R.id.tv_content, mCardNameString);
		
		mAtCard.setAdapter(mAdapter);
		
		mAtCard.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mAtCard.showDropDown();
			}
		});
		
		mAtCard.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String currentCard = mCardNameString.get(position);
				String[] strArray = currentCard.split(" ");
				mAtCard.setText(strArray[0]);
				Log.i("item clicked---", strArray[0]);
				
				 InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				 imm.hideSoftInputFromWindow(mAtCard.getWindowToken(), 0);
			}
		});

		// 初始化获取充值卡历史信息
		getHistoryCards();
	}

	@Override
	public void init() {
		
		findViewById(R.id.recharge_pay).setOnClickListener(this);
		
		checkBox3 = (CheckBox) findViewById(R.id.checkBox3);
		RelativeLayout ry3 = (RelativeLayout) findViewById(R.id.pay_thirdpart);

		checkBox2 = (CheckBox) findViewById(R.id.checkBox2);
		RelativeLayout ry2 = (RelativeLayout) findViewById(R.id.prepay_card);

		checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
		RelativeLayout ry1 = (RelativeLayout) findViewById(R.id.pay_juyoujin);

		ry1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (checkBox1.isChecked()) {
					checkBox1.setChecked(false);
				} else {
					setPayWay(1);
				}
			}
		});

		ry2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (checkBox2.isChecked()) {
					checkBox2.setChecked(false);
				} else {
					setPayWay(2);
				}
			}
		});

		ry3.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (checkBox3.isChecked()) {
					checkBox3.setChecked(false);
				} else {
					setPayWay(3);
				}
			}
		});

		mChargeSpinner = (Spinner) findViewById(R.id.spinner_charge);
		// 手动输入金额的数据源
		final String[] spinnerIteStrings = getResources().getStringArray(
				R.array.charges);
		mChareAdapter = new ArrayAdapter<String>(this, R.layout.drop_down_item,
				spinnerIteStrings);
		mChareAdapter.setDropDownViewResource(R.layout.drop_down_item);
		mChargeSpinner.setAdapter(mChareAdapter);
		mChargeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				String[] strArray = spinnerIteStrings[position].split(" ");
				mPayAmount = strArray[0];
				Log.i("mChargeSpinner--select", mPayAmount);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}

		});
	}
	
	public void setPayWay(int index){
		switch (index) {
		case 1:
			mCurrentPay = 1;
			checkBox1.setChecked(true);
			checkBox2.setChecked(false);
			checkBox3.setChecked(false);
			break;
		case 2:
			mCurrentPay = 2;
			checkBox1.setChecked(false);
			checkBox2.setChecked(true);
			checkBox3.setChecked(false);
			break;
		case 3:
			mCurrentPay = 3;
			checkBox1.setChecked(false);
			checkBox2.setChecked(false);
			checkBox3.setChecked(true);
			break;
		default:
			mCurrentPay = 0;
			checkBox1.setChecked(false);
			checkBox2.setChecked(false);
			checkBox3.setChecked(false);
			break;
		}
	}

	/**
	 * {"pageSize":10,"pageNo":1,"totalPages":1,"totalCount":2,"list":[{"id":2,
	 * "cardNo"
	 * :"123456987","cardOwner":"小黑"},{"id":1,"cardNo":"123456789","cardOwner"
	 * :"小红"}]}
	 * <br>获取历史充值卡信息
	 */
	public void getHistoryCards() {
		Listener<String> sListener = new Listener<String>() {
			@SuppressWarnings("rawtypes")
			@Override
			public void onResponse(String response) {
				dismissLoadingProgress();
				Log.i("getcards----success", response.toString());
				Gson gson = new Gson();
				java.lang.reflect.Type type = new TypeToken<Page>(){}.getType();
				Page page = gson.fromJson(response, type);
				@SuppressWarnings("unchecked")
				List<FuellingCard> cards = page.getList();
				for (int i = 0; i < cards.size(); i++) {
					// 卡号后面加上名字
					mCardNameString.add(cards.get(i).getCardNo() +" "+ cards.get(i).getCardOwner());
					// 卡号添加到数组，方便后续校验
					mCardStrings.add(cards.get(i).getCardNo());
				}
				mAdapter.notifyDataSetChanged();
			}
		};
		showLoadingProgress();
		
		String path = Config.URL_GET_CARDS;
		Map<String, String> map = new HashMap<String, String>();
		// 默认是第一页，每页20条，这里没有传参数，最多取20条
		// 如果需要传参数，可以使用Util.httpRequestToGetWithParams(url, l, el, map)
		map.put("pageNo", "1");
		map.put("pageSize", "20");
		Util.httpRequestToGetWithParams(path, sListener, this, map);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.recharge_pay://充值
			// 金额
			if (mIsManual) {
				mPayAmount = mEtInpu.getText().toString();
			}
			
			// 卡号非空验证
			if (mAtCard.getText().toString().length() == 0) {
				// 弹出提示对话框
				showAlertDialog(getString(R.string.commen_dialog_title_tip), getString(R.string.commen_dialog_message1));
				return;
			}
			
			// 金额非空验证
			if (mPayAmount.length() == 0) {
				// 弹出提示对话框
				showAlertDialog(getString(R.string.commen_dialog_title_tip), getString(R.string.commen_dialog_message2));
				return;
			}
			
			// 支付方式验证
			switch (mCurrentPay) {
			case 0:
				showAlertDialog(getString(R.string.commen_dialog_title_tip), getString(R.string.commen_dialog_message3));
				return;
			case 1:
				// 聚优金支付
				showToast("聚优金支付---敬请期待");
				break;
			case 2:
				// 预付卡支付
				break;
			case 3:
				// 银行卡支付
				// 卡号校验
				if (mCardNameString.size()==0 || !mCardStrings.contains(mAtCard.getText().toString().trim())) {
					checkFuellingCard(mAtCard.getText().toString().trim());
					return;
				}else{
					payForYeepay();
				}
				break;
			default:
				break;
			}
			break;
		default:
			break;
		}
	}
	
	/**
	 * 加油卡信息校验，对手动输入的卡号做校验
	 */
	public void checkFuellingCard(String carNo){
		Listener<String> sListener = new Listener<String>() {
			@Override
			public void onResponse(String response) {
				dismissLoadingProgress();
				Log.i("TAG----success", response.toString());
				Gson gson = new Gson();
				FuellingCard fuellingCard = gson.fromJson(response, FuellingCard.class);
				// 计算卡号后四位
				String cardNo = fuellingCard.getCardNo();
				String card4 = cardNo.substring(cardNo.length() - 4, cardNo.length());
				String info = String.format(getString(R.string.commen_dialog_message4), card4, fuellingCard.getCardOwner());
				
					AlertDialog.Builder builder = new AlertDialog.Builder(RechargeActivity.this, R.style.Custom_dialog);
					final AlertDialog alertDialog = builder.create();
					alertDialog.setCanceledOnTouchOutside(false);
					alertDialog.show();
					Window window = alertDialog.getWindow();
					View view = LayoutInflater.from(RechargeActivity.this).inflate(R.layout.dialog_alert, null);
					view.findViewById(R.id.ly_cancel).setVisibility(View.VISIBLE);
					view.findViewById(R.id.line).setVisibility(View.VISIBLE);
					
					((TextView)(view.findViewById(R.id.tv_title))).setText(getString(R.string.commen_dialog_title1));
					((TextView)(view.findViewById(R.id.tv_message))).setText(Html.fromHtml(info));
					
					view.findViewById(R.id.ly_cancel).setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							alertDialog.dismiss();
						}
					});
					
					view.findViewById(R.id.ly_ok).setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							alertDialog.dismiss();
							payForYeepay();
						}
					});
					window.setContentView(view);
					window.setLayout((int)(Util.getWidth(getApplicationContext()) * 0.8), WindowManager.LayoutParams.WRAP_CONTENT);
					
			}
		};
		showLoadingProgress();
		String path = Config.URL_CHECK_CARD;
		Map<String, String> map = new HashMap<String, String>();
		map.put("cardNo", carNo);
		map.put("terminalId", Util.getDeviceID(RechargeActivity.this));
		Util.httpStringPost(path, sListener, this, map);
	}
	
	

	public void payForYeepay(){
		Listener<String> sListener = new Listener<String>() {
			@Override
			public void onResponse(String response) {
				dismissLoadingProgress();
				Log.i("TAG----success", response.toString());
				HashMap<String, String> result = new Gson().fromJson(response.toString().trim(),
						new TypeToken<HashMap<String, String>>() {
						}.getType());
				
				if (result != null && result.containsKey("paymentUrl")) {
					Intent intentToPay = new Intent(RechargeActivity.this, YeepayActivity.class);
					intentToPay.putExtra("paymentUrl", result.get("paymentUrl"));
					startActivityIn(intentToPay);
				}
			}
		};
		showLoadingProgress();
		String path = Config.URL_YEEPAY;
		Map<String, String> map = new HashMap<String, String>();
		map.put("amount", mPayAmount);
		map.put("account", mAtCard.getText().toString());
		map.put("terminalId", Util.getDeviceID(RechargeActivity.this));
		map.put("transactionCode", "GAS001");
		map.put("productCode", "ZHICHONG");
		Util.httpStringPost(path, sListener, this, map);
	}
	
	
	
	@Override
	protected void onResume() {
		super.onResume();
		if(mAtCard.getText().length() != 0)
		mAtCard.setText("");
	}

}
